package com.ai.aichat.controller;

import com.ai.aichat.entity.Users;
import com.ai.aichat.service.JwtService;
import com.ai.aichat.util.Result;
import lombok.Data;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

// 登录请求/响应 DTO
@Data
class LoginRequest { private String username; private String password; }
@Data class TokenResponse { private String token; public TokenResponse(String t){this.token=t;} }

// 负责接收用户名密码并签发 JWT 的控制器
@RestController
@RequestMapping("/api/auth")
public class AuthController {
    private final AuthenticationManager authenticationManager; // 委托给 Security 框架完成认证
    private final JwtService jwtService;                        // 生成 JWT 的服务

    // 从 AuthenticationConfiguration 获取 AuthenticationManager
    public AuthController(AuthenticationConfiguration config, JwtService jwtService) throws Exception {
        this.authenticationManager = config.getAuthenticationManager();
        this.jwtService = jwtService;
    }

    // 登录端点：认证成功则返回 token，失败由框架抛异常并转换为 401
    @PostMapping("/login")
    public TokenResponse login(@RequestBody LoginRequest req) {
        Authentication auth = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(req.getUsername(), req.getPassword())
        );
        String token = jwtService.generateToken(auth.getName(), auth.getAuthorities());
        return new TokenResponse(token);
    }
}
